<template>
    <el-form ref="loginFormRef" :model="loginUser" :rules="rules" label-width="100px" class="loginForm sign-in-form">
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="loginUser.email" placeholder="Enter Email..."></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="loginUser.password" type="password" placeholder="Enter Password..."></el-input>
        </el-form-item>

        <el-form-item>
            <el-button @click="handleLogin(loginFormRef)" type="primary" class="submit-btn">提交</el-button>
        </el-form-item>

        <!-- 找回密码 -->
        <div class="tiparea">
            <p>忘记密码？ <a @click="forgotPassword">立即找回</a></p>
        </div>
    </el-form>
</template>

<script lang="ts" setup>
import { ref, getCurrentInstance, defineProps } from "vue";
import { FormInstance, ElMessage } from 'element-plus'
import { useRouter } from "vue-router";
const proxy = getCurrentInstance() as any;
defineProps({
    loginUser: {
        type: Object,
        required: true,
    },
    rules: {
        type: Object,
        required: true,
    },
});
const router = useRouter();
//@ts-ignore
const { $axios } = proxy.appContext.config.globalProperties
const loginFormRef = ref<FormInstance>();
// 触发登录方法
const handleLogin = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid: boolean) => {
        if (valid) {
            console.log(proxy.ctx.loginUser);

            $axios.post("/api/v1/auth/login", proxy.ctx.loginUser).then((res: any) => {
                console.log(res);
                if (res.success) {
                    ElMessage.success('登录成功');
                    const { token } = res;
                    localStorage.setItem('user-token', token)
                    setTimeout(() => {
                        router.push('/')
                    }, 1000)
                }
            })
        } else {
            console.log("error submit!!");
            return false;
        }
    })
};
//找回密码
const forgotPassword = () => {
    router.push('/forgotpassword')
}
</script>
<style scoped>
/* form */
.loginForm {
    margin-top: 20px;
    background-color: #fff;
    padding: 20px 40px 20px 20px;
    border-radius: 5px;
    box-shadow: 0px 5px 10px #cccc;
}

.submit-btn {
    width: 100%;
}

.tiparea {
    text-align: right;
    font-size: 12px;
    color: #333;
}

.tiparea p a {
    color: #409eff;
}
</style>